package cnt5106.p2p.peer.filesystem;


public class ChunkList 
{
	private boolean full = false;     //  indicate the completion of transmission
	private int base = 0;
	private long storedChunkNum = 0;
	private long chunkNum = -1;    // total number of chunks
	public static boolean[] list = null;  // each bit specify a chunk's state: got/not got /////////////////////////
	
	
	
	public ChunkList(long fileLength)
	{
		System.out.println("The file length is " + fileLength);//////////////////////////////////////////////////////
		chunkNum = ((fileLength%(100*1024)) == 0) ? (fileLength/(100*1024)) : (fileLength/(100*1024)) + 1;
		System.out.println("The chunk number in chunkList is " + chunkNum);//////////////////////////////////////////
		list = new boolean[(int) chunkNum];
	}
	
	/*
	 *   get the number of chunks
	 */
	public int getLength()
	{
		return list.length;
	}
	
	/*
	 *   check if the chunk of given index is existed
	 */
	public boolean checkChunk(int indx)
	{
		return list[indx];
	}
	
	/*
	 *   set a chunk slot to be filled
	 */
	public void setChunk(int num)
	{
		if (++ storedChunkNum == chunkNum)
			full = true;
		list[num] = true;
	}
	
	
	/*
	 *  return the index of an empty chunk slot
	 */
	public int getEmptyChunk()
	{
		int index = -1;   // the index of empty chunk slot
		for(int i=base; i<list.length; i++)
		{
			if (list[i] == false){
					index = i;
					//if (i == list.length - 1)
						//full = true;
					base = i++;
					break;
			}
		}
		return index;
	}
	
	/*
	 *   check if all the chunk slots are filled
	 */
	public boolean isFinished ()
	{
		return full;
	}
}
